package code.sbxj.qwd.com.sbxj;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.CacheDiskUtils;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.UUID;


@ContentView(R.layout.activity_devicedetail)
public class DeviceDetailActivity extends BaseActivity {

    JSONObject data;

    @ViewInject(R.id.ed)
    private EditText ed;

    @ViewInject(R.id.state1)
    private TextView state1;

    @ViewInject(R.id.state2)
    private TextView state2;

    @ViewInject(R.id.photo)
    private TextView photo;

    @ViewInject(R.id.ed_error)
    private EditText ed_error;

    @ViewInject(R.id.save)
    private TextView save;

    @ViewInject(R.id.gridview)
    private GridView gridview;

    @ViewInject(R.id.saveoffline)
    private TextView saveoffline;

    ArrayList<String> Imagepath = new ArrayList<>();

    int checkid = 1;
    gridviewAdapter adapter_gridview;

    String myuuid = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            data = new JSONObject(getIntent().getExtras().getString("data"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        setTitleText("检查项：" + data.optString("name"));
        initView();
        getMyUUID();
    }


    void initView() {

        if (data.optBoolean("sense")) {
            state1.setVisibility(View.VISIBLE);
            state2.setVisibility(View.VISIBLE);
            ed.setVisibility(View.GONE);
        } else {
            state1.setVisibility(View.GONE);
            state2.setVisibility(View.GONE);
            ed.setVisibility(View.VISIBLE);
        }


        state1.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        state1.setBackgroundResource(R.drawable.roundshape);
                        state2.setBackgroundResource(R.drawable.roundshape1);
                        checkid = 1;
                        ed_error.setVisibility(View.GONE);
                    }
                }
        );

        state2.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        state1.setBackgroundResource(R.drawable.roundshape1);
                        state2.setBackgroundResource(R.drawable.roundshape);
                        checkid = 2;
                        ed_error.setVisibility(View.VISIBLE);
                    }
                }
        );

        ed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(final Editable editable) {
                try {
                    data.put("exception", editable.toString());

                    double max = data.optDouble("upperLimit");
                    double low = data.optDouble("lowerLimit");
                    if (editable.toString().length() == 0) {
                        ed_error.setVisibility(View.GONE);
                        return;
                    }
                    if (Double.parseDouble(editable.toString()) > max || Double.parseDouble(editable.toString()) < low) {

                        ed_error.setVisibility(View.VISIBLE);
                        save.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Imagepath.size() == 0) {

                                    Save();
                                } else {

                                    Upload();
                                }

                            }
                        });
                    } else {
                        ed_error.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (Imagepath.size() == 0) {

                    Save();
                } else {

                    Upload();
                }
            }
        });

        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = new File(Environment.getExternalStorageDirectory(), "/sbxj/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                Uri imageUri = Uri.fromFile(file);
                getTakePhoto().onPickFromCapture(imageUri);
            }
        });
        adapter_gridview = new gridviewAdapter();
        gridview.setAdapter(adapter_gridview);


        saveoffline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(ed.getVisibility()==View.VISIBLE){
                    if(ed.getText().toString().length()==0){
                        Toast.makeText(DeviceDetailActivity.this,"请填写完整后提交",Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                JSONArray array = CacheDiskUtils.getInstance().getJSONArray("uploaddata");

                if (array == null) {
                    array = new JSONArray();
                }

                JSONObject result = new JSONObject();
                try {
                    result.put("taskId", (int) CacheDiskUtils.getInstance().getSerializable("task_id"));
                    result.put("name",data.optString("name"));
                    result.put("deviceId", getIntent().getExtras().getInt("deviceId"));
                    result.put("checkItemId", data.optInt("id"));
                    result.put("senseStatus", checkid == 1 ? true : false);
                    result.put("des", ed_error.getText().toString());
                    result.put("processAttachId", myuuid);
                    result.put("value_status", ed.getText().toString());


                    JSONObject obj = new JSONObject();
                    obj.put("des", ed_error.getText().toString());
                    result.put("exceptionOrder", obj);

                    JSONArray imgarray = new JSONArray();
                    for (String path : Imagepath) {
                        imgarray.put(path);
                    }
                    result.put("imgarray", imgarray);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                array.put(result);

                CacheDiskUtils.getInstance().put("uploaddata", array);
//                Toast.makeText(x.app(), "保存完毕", Toast.LENGTH_LONG).show();
                finish();
            }
        });
    }

    private void configCompress(TakePhoto takePhoto) {
        int maxSize = 302400;
        int width = 1000;
        int height = 1000;
        CompressConfig config;
        config = new CompressConfig.Builder().setMaxSize(maxSize)
                .create();
        takePhoto.onEnableCompress(config, true);


    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);

        Imagepath.add(result.getImage().getCompressPath());

        adapter_gridview.notifyDataSetChanged();

    }


    class gridviewAdapter extends BaseAdapter {


        @Override
        public int getCount() {
            return Imagepath.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = getLayoutInflater().inflate(R.layout.grideviewiterm, null);

            ImageView iv = view.findViewById(R.id.iv);
            ImageOptions imageOptions = new ImageOptions.Builder()
                    .setIgnoreGif(false)//是否忽略gif图。false表示不忽略。不写这句，默认是true
                    .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                    .build();
            x.image().bind(iv, Imagepath.get(position), imageOptions);
            return view;
        }
    }

    private void Save() {

        if(ed.getVisibility()==View.VISIBLE){
            if(ed.getText().toString().length()==0){
                Toast.makeText(this,"请填写完整后提交",Toast.LENGTH_SHORT).show();
                return;
            }
        }
        ShowLoading();
        RequestParams params = new RequestParams(Config.BaseUrl + "checkRecord/add");
        params.setAsJsonContent(true);
        JSONObject result = new JSONObject();
        try {
            result.put("taskId", getIntent().getExtras().getInt("taskId"));
            result.put("deviceId", getIntent().getExtras().getInt("deviceId"));
            result.put("checkItemId", data.optInt("id"));
            result.put("senseStatus", checkid == 1 ? true : false);
            result.put("des", ed_error.getText().toString());
            result.put("processAttachId", myuuid);
            result.put("value_status", ed.getText().toString());


            JSONObject obj = new JSONObject();
            obj.put("des", ed_error.getText().toString());
            result.put("exceptionOrder", obj);


        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.setUseCookie(true);
        params.addHeader("cookie", CacheDiskUtils.getInstance().getString("cookie"));
        params.setBodyContent(result.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Log.e("result_save", result);
                Toast.makeText(x.app(), "提交成功！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                CancleLoading();
                if (ex.toString().contains("不在巡检任务时间")) {
                    Toast.makeText(x.app(), "不在巡检任务时间范围内", Toast.LENGTH_LONG).show();
                }else if (ex.toString().contains("重复")) {
                    Toast.makeText(x.app(), "请勿重复提交", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {
                CancleLoading();
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

                CancleLoading();
            }
        });
    }

    private void Upload() {
        ShowLoading();
        RequestParams params = new RequestParams(Config.BaseUrl + "attachment/upload");
        params.setUseCookie(true);
        params.addHeader("cookie", CacheDiskUtils.getInstance().getString("cookie"));
        params.addBodyParameter("uuid", myuuid);
        int i = 0;
        for (String path : Imagepath) {
            params.addBodyParameter("file", new File(path));
            i++;
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                CancleLoading();
                Toast.makeText(DeviceDetailActivity.this, "图片上传完毕", Toast.LENGTH_SHORT).show();
                Save();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }


    TakePhoto takePhoto;

    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }

        configCompress(takePhoto);
        return takePhoto;
    }

    private String getMyUUID() {

        UUID uuid = UUID.randomUUID();

        myuuid = uuid.toString();

        return myuuid;

    }
}
